package io.gitee.zhangbinhub.acp.cloud

import io.gitee.zhangbinhub.acp.cloud.loadbalancer.AcpLoadBalancerAlgorithm
import io.gitee.zhangbinhub.acp.cloud.loadbalancer.AcpNacosLoadBalancer
import io.gitee.zhangbinhub.acp.cloud.loadbalancer.AcpServiceInstanceFilter
import io.gitee.zhangbinhub.acp.cloud.loadbalancer.DefaultLoadBalancerAlgorithm
import org.noear.solon.annotation.Bean
import org.noear.solon.annotation.Configuration
import org.noear.solon.annotation.Inject
import org.noear.solon.cloud.impl.CloudLoadStrategy

/**
 * @since JDK 17
 */
@Configuration
class AcpCloudLoadBalancerAutoConfiguration {
    @Bean(index = Int.MAX_VALUE)
    fun defaultLoadBalancerAlgorithm(): AcpLoadBalancerAlgorithm = DefaultLoadBalancerAlgorithm()

    @Bean
    fun acpNacosLoadBalancer(
        @Inject acpServiceInstanceFilters: MutableList<AcpServiceInstanceFilter>,
        @Inject acpLoadBalancerAlgorithms: MutableList<AcpLoadBalancerAlgorithm>
    ): CloudLoadStrategy = mutableMapOf<String, AcpLoadBalancerAlgorithm>().apply {
        acpLoadBalancerAlgorithms.forEach { acpLoadBalancerAlgorithm ->
            if (!this.containsKey(acpLoadBalancerAlgorithm.getServiceId())) {
                this[acpLoadBalancerAlgorithm.getServiceId()] = acpLoadBalancerAlgorithm
            }
        }
    }.let { AcpNacosLoadBalancer(acpServiceInstanceFilters, it) }
}
